const express = require('express')
const multer = require('multer')//express处理文件包，文档https://github.com/expressjs/multer/
const path = require('path')
const atrributeId = require('../../tools/atrributeId.js')
const database = require('../../database')

const router = express.Router()
//上传文件的配置
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, './public/blog/cover')//保存路径
    },
    filename: (req, file, cb) => {
        let extname = path.extname(file.originalname)//获取文件后缀
        let originalname = path.basename(file.originalname, extname)//文件名可别整空格，不然渲染不出来
        cb(null, originalname+Date.now()+extname)//文件名，时间戳不重复处理
    }
})
const upload = multer({ storage: storage })

router.post('/uploadBlog', upload.single('file'), async (request, response) => {
    let blog = request.body
    blog.url = 'http://localhost/image?url='+request.file.path
    blog.id = await atrributeId()//返回promise
    blog.timeStamp = new Date().toLocaleString()//发布时间
    const sql = 'insert into blogs values(?, ?, ?, ?, ?, ?, ?)'
    //直接存html
    database.query(sql, [blog.id, blog.title, blog.type, blog.url, blog.description, blog.html, blog.timeStamp], (error, result) => {
        if(error) {
            console.log(error.message)
            response.status(417).end()
        } else {
            response.end()
        }
    })
})

module.exports = router